package ejb;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.transaction.UserTransaction;


import model.Category;
import model.Mycomment;
import model.Myuser;
import model.Target;

@Stateless
public class TargetFacadeEJB implements TargetFacadeEJBRemote{

	@PersistenceContext
	EntityManager em;  
	@Override
	public ArrayList<Target> getAllTargets() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Target> getAllTargetsByRate() {
		List<Target> rated=null;
		try{
			//String sql="select t from Target t";
			//String sql="select m.targetBean from Mylike m where ( select m.targetBean, count(*) from Mylike m group by m.targetBean order by count(*) )>0";
			String sql=" select m.targetBean from Mylike m group by m.targetBean ";
			
			//order by count(m.myuser)
			Query query=em.createQuery(sql);
			
			rated=(List<Target>)query.getResultList();
			//ResultSet rs=query.getResultSet();
//			for (Object[] items : temp) {
//			    Target t = (Target) items[0];
//			   // int count=Integer.parseInt(items[1].toString());
//			    rated.add(t);
//			}
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return rated;
	}

	@Override
	public List<Target> getAllTargetsLikedByOne(Myuser user) {
		List<Target> mylikes=null;
		try{
			String sql=" select t from Target t, Mylike m where t=m.targetBean and m.myuser=:user ";
			
			Query query=em.createQuery(sql);
			query.setParameter("user", user);
			mylikes=(List<Target>)query.getResultList();
		}
		catch(Exception e){
			e.printStackTrace();
			//System.out.print("in CEJB!!!***");
		}
		return mylikes;

	}
	
	@Override
	public List<Target> getAllTargetsMerchantByOne(Myuser user) {
		List<Target> mymerchant=null;
		try{
			String sql="select t from Target t where t.myuser =:u";
			Query query=em.createQuery(sql);
			query.setParameter("u", user);
			mymerchant=(List<Target>)query.getResultList();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return mymerchant;
	}
	
	
	@Override
	public List<Target> getTargetByCategotyID(int categoryID) {
		List<Target> catetar=null;
		try{
			String sql="select ct.target from CateTarget ct where ct.category.categoryid=:id";
			Query query=em.createQuery(sql);
			query.setParameter("id", categoryID);
			catetar=query.getResultList();
		}catch(Exception e){
			e.printStackTrace();
		}
		return catetar;
	}

	@Override
	public List<Mycomment> getCommentOfTarget(Target target) {
		List<Mycomment> comment=null;
		try{
			String sql="select mc from Mycomment mc where mc.targetBean=:target";
			Query query =em.createQuery(sql);
			query.setParameter("target", target);
			comment=query.getResultList();
		}catch(Exception e){
			e.printStackTrace();
		}
		return comment;
	}
	
	
	@Override
	 public Target getTarget(){
			
			Target t = (Target)em.createQuery("select t from Target t").getResultList().get(11);
			
			return t;
		}
	    
	    
	    @Override
		public String getAllTargetInfo() {
	    	try
	    	{
				
				List<Target> arrTest = em.createQuery("select t from Target t").getResultList();

				System.out.println(" total compnies size:"+arrTest.size());
				 String str = "";
		         for (Target obj : arrTest) {
		        	 str += obj.getTargetname()+ " " + obj.getInfo()+ " " + obj.getLocation() + " " + obj.getTargetid() + " " + obj.getActivestatus() + "<br>";
		         }
				return str;
			}
	    	catch (RuntimeException re)
			{
					System.out.println("getStudentInfo() failed : \n msg:"+ re.getMessage());
				throw re;
			}
		}
		
		@Override
		public ArrayList<Target> searchTarget(String input){
			
			char[] temp = input.toCharArray();
			for(int i=0;i<temp.length;i++){
				temp[i] =Character.toUpperCase(temp[i]);
			}
			String result = new String(temp);
			
			try
	    	{
				List<Target> arrTest = em.createQuery("select t from Target t").getResultList();
				
				ArrayList<Target> r = new ArrayList<Target>();
				 
		         for (Target obj : arrTest) {
		        	 
		        	 char[] tempTargetName = obj.getTargetname().toCharArray();
		        	 char[] tempTargetLocation = obj.getLocation().toCharArray();
		        	 char[] tempTargetInfo = obj.getInfo().toCharArray();

		        	 for(int i=0;i<tempTargetName.length;i++){
		        		 tempTargetName[i] =Character.toUpperCase(tempTargetName[i]);
		 			}
		 			String tempTargetNameS = new String(tempTargetName);
		 			
		 			 for(int i=0;i<tempTargetLocation.length;i++){
		 				tempTargetLocation[i] =Character.toUpperCase(tempTargetLocation[i]);
		 			}
		 			String tempTargetLocationS = new String(tempTargetLocation);
		 			
		 			 for(int i=0;i<tempTargetInfo.length;i++){
		 				tempTargetInfo[i] =Character.toUpperCase(tempTargetInfo[i]);
			 			}
			 		String tempTargetInfoS = new String(tempTargetInfo);
		 			
		        	 if(tempTargetNameS.contains(result) || tempTargetLocationS.contains(result) || tempTargetInfoS.contains(result)) {
		        		 r.add(obj);
		        	 }   	
		         }
				return r;
			}
	    	catch (RuntimeException re)
			{
					System.out.println("getStudentInfo() failed : \n msg:"+ re.getMessage());
				throw re;
			}	
		}
	    
		@Override
		public boolean checkIfExist(String username) {

			String sql="select t from Target t where t.targetname=:name";
	    	Query query= em.createQuery(sql);
	    	query.setParameter("name", username);
	    	if(query.getResultList().isEmpty()){
	    		return false;
	    	}
	    	else return true;
		}
		
		@Override
		public boolean checkIfExistByID(int targetid){
			
			String sql="select t from Target t where t.targetid=:id";
	    	Query query= em.createQuery(sql);
	    	query.setParameter("id", targetid);
	    	if(query.getResultList().isEmpty()){
	    		return false;
	    	}
	    	else return true;
			
		}
		
		
		@Override
		public Target queryByTargetName(String name){

			Target t = new Target();
			try
	    	{
				String sql = "select t from Target t where t.targetname=:name";
				Query query = em.createQuery(sql);
				query.setParameter("name", name);
				t = (Target)query.getResultList().get(0);
		    }
	    	catch (RuntimeException re)
			{
					System.out.println("getStudentInfo() failed : \n msg:"+ re.getMessage());
				throw re;
			}
			return t;
		}
		
		@Override
		public Target queryByTargetID(int tid){

			Target t = new Target();
			try
	    	{
				String sql = "select t from Target t where t.targetid=:id";
				Query query = em.createQuery(sql);
				query.setParameter("id", tid);
				t = (Target)query.getResultList().get(0);
		    }
	    	catch (RuntimeException re)
			{
					System.out.println("queryByTargetID() failed : \n msg:"+ re.getMessage());
				throw re;
			}
			return t;
			
		}
		
		@Override
		public String getResultNum(ArrayList<Target> result){
			String str = "Found " + result.size() + " results";
			return str;
		}

		@Override
		public List<Target> getAllTargetWithMchtInfo() {
			String sql = "select t from Target t where t.mchtinfo<>:info";
			Query query = em.createQuery(sql);
			query.setParameter("info", "");
			return (List<Target>) query.getResultList();
		}	
	
}
